<template>
    <div style="" class="formBox">
        <rx-error :message="errorMessage" v-if="!taskStatus"></rx-error>

        <bpm-header :title="bpmInst.subject" :user="bpmInst.createBy" v-if="taskStatus"></bpm-header>

        <div class="bpm-task-content" v-if="taskStatus">
            <a-tabs class="rx-a-tabs" default-active-key="details" @change="changeTabs($event)">
                <div slot="tabBarExtraContent" class="tabs-toolbar">
                    <task-tool-bar ref="taskToolBar" :bpmTaskDetail="bpmTaskDetail" :taskConfig="taskConfig" @showBpmCommu="showBpmCommu"/>
                </div>
                <a-tab-pane key="details" :tab="i18n('list.detail', '详情')">
                    <div class="tab-center-bg">
                        <div class="tab-center-content" :class="{'tab-center-content-show':showHistory}">
                            <div class="tab-center">
                                <!--单据实例信息-->
                                <bpm-inst-info :bpmInst="bpmInst"/>
                                <div style="padding:0 10px 10px">
                                    <!--显示提交的沟通-->
                                    <task-commu :task-linkup-param.sync="taskLinkupParam"
                                                @commuTaskRevoked="reloadTaskInfo()"/>
                                    <!--表单-->

                                    <!--<rx-forms ref="rxForms"  />-->
                                    <rx-forms ref="rxForms" v-if="processConfig.formType=='online'"></rx-forms>
                                    <component ref="customForm" :is="formComponent" :pk="pk"
                                               v-else-if="processConfig.formType=='custom'"></component>
                                    <component ref="outSideUrlForm" :is="formComponent"
                                               :pk="pk" :showUrl="outSideUrl" :urlParamData="urlParamData"
                                               v-else-if="urlParamsShow"></component>

                                    <!--任务沟通-->
                                    <bpm-commu-history
                                        :inst-id="instId"
                                        :bpm-task="bpmTask"
                                        :bpmTaskDetail="bpmTaskDetail"
                                        :bpmCommuShow.sync="bpmCommuShow"
                                        @doReplyCommu="doReplyCommu"/>
                                    <!--留言-->
                                    <bpm-inst-msgs :instId="instId" :msg-show.sync="msgShow"/>
                                    <bpm-inst-logs :instId="instId" :log-show="logShow"/>
                                </div>
                            </div>
                        </div>
                        <div class="bpm-history-button" @click="foldRight">
                            <i class="iconfont iconVue3jpaas-icon_shenpilishi"></i>
                        </div>
                        <div class="bpm-task-history" :class="{'bpm-task-show':showHistory}">
                            <!--审批历史-->
                            <div style="width: 340px;height: 100%;">
                                <div class="bpm-task-history-text">
                                    <span>{{i18n('list.appHistory', '审批历史')}}</span>
                                    <span class="bpm-history-close" @click="foldRight">
                                        <a-icon type="close" />
                                    </span>
                                </div>
                                <bpm-history
                                    :inst-id="instId"
                                    :bpm-task="bpmTask"
                                    :historyShow.sync="historyShow"/>
                            </div>

                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="flowChart" :tab="i18n('list.flowChart', '流程图')">
                    <bpm-image-view v-if="isShowImage" :task-id="taskId" :preview="false" :formData="formData"></bpm-image-view>
                </a-tab-pane>
            </a-tabs>
        </div>

    </div>

</template>
<script>
import {RxDialog, Util, RxFit, RxTextBoxList, RxUserInfo} from '@lowcode/jpaas-common-lib';
import BpmtaskApi from "@/api/bpm/core/bpmTask";
import BpmInstMsgs from "./BpmInstMsgs"
import BpmInstLogs from "./BpmInstLogs";
import TaskToolBar from "./TaskToolBar";
import bpmHistory from "@/views/modules/bpm/core/component/bpmHistory";

import RxForms from "./RxForms";
import BpmInstInfo from "./BpmInstInfo";
import BpmCheckHistory from "./BpmCheckHistory";
import BpmCommuHistory from "./BpmCommuHistory";
import TaskCommu from "./TaskCommu";
import TaskCommuReply from "./TaskCommuReply";
import FormPcApi from "@/api/form/core/formPc.js";
import userState from "@/assets/js/userState";
import RxError from "../../share/rx-error";
import BpmStatus from "@/views/modules/bpm/core/component/BpmStatus";
import bpmHeader from "@/views/modules/bpm/core/component/bpmHeader";
import BpmImageView from "@/views/modules/bpm/comps/BpmImageView";
import FlowUtil from "@/views/modules/bpm/js/FlowUtil";
export default {
    name: "BpmTaskStart",
    mixins: [userState,FlowUtil],
    components: {
        RxError,bpmHistory,
        TaskCommuReply,
        TaskCommu,
        BpmCheckHistory,
        BpmCommuHistory,
        BpmInstInfo,
        RxDialog,
        TaskToolBar,
        BpmInstMsgs,
        BpmInstLogs,
        RxFit,
        RxTextBoxList,
        RxForms,
        RxUserInfo,
        BpmStatus,
        bpmHeader,
        BpmImageView
    },
    props: {
        taskId: {
            type: String,
            required: true
        },
        instId: {
            type: String,
            required: true
        },
        layerid: String,
        lydata: Object,
        destroy: Function
    },
    computed:{
        showStatus() {
            if (!this.processConfig.switchOptions) {
                return true;
            }
            let rtn = this.processConfig.switchOptions.includes("showStatus");
            return rtn;

        }
    },
    data() {
        return {
            collapsed:false,
            title: this.i18n('list.taskDetail','任务详情'),
            msgTypes: '',
            opinion: '',
            checkType: 'AGREE',
            historyShow: false,
            bpmCommuShow:false,
            msgShow: false,
            bpmInst: {instId: ''},
            bpmTask: {taskId: this.taskId},
            isCanBack: false,
            canCheck: true,
            canRecorveLinkup: false,
            bpmCmTaskInfos: [],
            isAllowLinkup: true,
            backPathResult: {},
            nodeExecutors: [],
            processConfig: {
                formType: "online"
            },
            taskConfig: {},
            bpmTaskDetail: {},
            msgSubmitting: false,
            logShow: false,
            //任务沟通参数
            taskLinkupParam: {
                canStartLinkup: false,
                canRevokeLinkup: false,
                canReplyLinkup: false,
                bpmCmTaskInfos: []
            },
            //回复沟通任务
            taskLinkupReply: {
                msgTypes: '',
                opinion: '',
                lpReplyVisible: false,
            },
            formComponent: "",
            outSideUrl:"",
            urlParamData:[],
            urlParamsShow:false,
            pk: "",
            taskStatus: true,
            errorMessage: "",
            //根实例
            rootVm: true,
            status: '',
            showHistory:false,
            formData:{},
            isShowImage:false
        }
    },
    beforeDestroy(){
        this.$bus.off("openFormDialogEvent");
    },
    created() {
        this.loadTaskInfo();
        if(this.$bus.instance){
            this.$bus.on("openFormDialogEvent",(obj)=>{
                this.openFormDialogEvent(obj);
            });
        }
        let showTaskHistory=Util.getKey("showTaskHistory");
        if(showTaskHistory){
            this.showHistory=showTaskHistory=="YES";
        }
        this.updateReceiversReaded();
    },
    methods: {
        /**
         * 如果是沟通任务，更新为已阅
         */
        updateReceiversReaded(){
            BpmtaskApi.updateReceiversReaded(this.taskId,2);
        },
        foldRight(){
            this.showHistory = !this.showHistory;
            let showTaskHistory=this.showHistory?'YES':'NO';
            Util.setKeyVal("showTaskHistory",showTaskHistory);
        },
        changeTabs(key){
            if(key=='flowChart'){
                this.getFormData();
            }else {
                this.isShowImage=false;
            }
        },
        getFormData(){
            if (this.processConfig.formType == "custom") {
                this.formData = this.$refs.customForm.getData();
            }else if (this.processConfig.formType == "outsideUrl") {
                this.formData = this.$refs.outSideUrlForm.getData();
            } else {
                this.formData = this.$refs.rxForms.getData();
            }
            this.isShowImage=true;
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmInst",key);
        },
        openFormDialogEvent(formBoList){
            var action="boList";
            if (formBoList.isTreeDlg == "YES") {
                action="boListTree";
            }
            let openObj=this.$router.resolve({
                name:'openFormDoc',
                params:{
                    pkId: formBoList.id
                },
                query:{
                    action:action,
                    isDialog:formBoList.isDialog
                }
            });
            let href=openObj.href ;
            window.open(href,"_blank" );
        },
        showBpmCommu(val){
            this.bpmCommuShow=true;
        },
        doReplyCommu(val){
            this.bpmCommuShow=false;
            this.$refs.taskToolBar.doReplyCommu();
        },
        //刷新任务
        async loadTaskInfo() {
            let self = this;
            if (!this.taskId) {
                this.taskId = this.$route.params.taskId;
            }
            if (!this.instId) {
                this.instId = this.$route.params.instId;
            }
            let res = await BpmtaskApi.getAllDetail(this.taskId);
            if (!res.success) {
                this.taskStatus = false;
                this.errorMessage = res.message;
                return;
            }
            this.status = res.data.bpmInst.status;
            this.bpmTaskDetail = res.data;

            if (res.data.bpmTask == null) {
                if (self.destroy) {
                    this.$notification.open({
                        message: self.$ti18('rxMsa.actionTips','操作提示'),
                        description:
                            self.i18n('completed','当前任务已经完成或删除，请刷新数据界面再操作！'),
                        icon: <a-icon type="smile" style="color: #108ee9"/>,
                    });
                    Util.closeWindow(self, "ok", {});
                    return;
                } else {
                    alert(self.i18n('completed','当前任务已经完成或删除，请刷新数据界面再操作！'));
                    window.close();
                }
            }else {
                //当前实例为锁定 任务不是锁定 则显示为运行中
                if(this.status =='LOCKED' && res.data.bpmTask.status!='LOCKED'){
                    this.status ='RUNNING';
                }
                else if(this.status =='RUNNING' && res.data.bpmTask.status=='LOCKED'){
                    //当前实例为运行中 任务是锁定 则显示为锁定
                    this.status ='LOCKED';
                }
            }

            Object.assign(self, res.data);
            var curUser = this.user;
            let taskConfig = res.data.taskConfig;
            var contextData = {
                type: "usetask",
                curUserId: curUser.userId,
                curUserName: curUser.fullName,
                account: curUser.account,
                deptId: curUser.deptId,
                nodeId: self.bpmTask.key,
                nodeName: self.bpmTask.name,
                instId: self.instId,
                defId: self.bpmInst.defId,
                instNo: self.bpmInst.billNo,
                taskId: self.taskId,
                tenantId: curUser.tenantId,
                tenantLabel: curUser.tenantLabel,
                opinionHistorys: res.data.bpmCheckHistories,
                alias: taskConfig.alias,
                subject:taskConfig.subject
            };
            self.handFormConfig(res.data.processConfig, taskConfig, res.data.bpmInst);
            if (this.processConfig.formType == 'online') {
                this.$nextTick(function () {
                    self.$refs.rxForms.setData(res.data.formData.data, false, contextData);
                })
            }
        },
        loadUrlView()  {
            // 路由懒加载
            return require('@/layouts/UrlView.vue').default;
        },
        getFormPc(formId){
            var self_=this;
            if(!formId){
                self_.urlParamsShow=true;
                return;
            }
            FormPcApi.get(formId).then(res =>{
                if(!res.success){
                    self_.$message.error(self_.i18n('URLFail','获取外部URL表单失败：')+res.message);
                    return;
                }
                let data =res.data;
                if(data.urlParams){
                    self_.replaceUrlParmaVal(data.urlParams);
                }
                self_.urlParamsShow=true;
                return;
            });
        },
        replaceUrlParmaVal(urlParams){
            var curUser=this.user;
            var contextData={
                userId:curUser.userId,
                defId:this.bpmInst.defId,
                instId:this.instId,
                taskId:this.taskId,
                nodeId:this.bpmTask.key
            }
            var urlParamData=JSON.parse(urlParams);
            for(let i=0;i<urlParamData.length;i++){
                let param=urlParamData[i];
                if(param.paramType){
                    let val = contextData[param.paramKeyVal];
                    param.paramKeyVal=val;
                }
            }
            this.urlParamData=urlParamData;
        },
        loadView(view) { // 路由懒加载
            return () => import(`@/views/${view}`);
        },
        //处理表单配置。
        handFormConfig(conf, taskConfig, bpmInst) {
            var config = Util.deepClone(this.processConfig);
            this.processConfig = Object.assign(config, conf);
            if (!this.processConfig.formType) {
                this.processConfig.formType = "online"
            }
            //startForm
            if (taskConfig.form.formpc && taskConfig.form.formpc.length > 0) {
                var form = taskConfig.form.formpc[0];
                if (form && form.type == "custom") {
                    this.pk = bpmInst.busKey;
                    this.processConfig.formType = "custom";
                    this.formComponent = this.loadView(form.component);
                    return;
                }
                if(form && form.type=="outsideUrl"){
                    this.pk = bpmInst.busKey;
                    this.outSideUrl=form.component;
                    this.processConfig.formType="outsideUrl";
                    this.formComponent=this.loadUrlView();
                    this.getFormPc(form.id);
                    return;
                }
            }
            //获取全局。
            if (conf.globalForm.formpc && conf.globalForm.formpc.length > 0) {
                var form = conf.globalForm.formpc[0];
                if (form && form.type == "custom") {
                    this.pk = bpmInst.busKey;
                    this.processConfig.formType = "custom";
                    this.formComponent = this.loadView(form.component);
                    return;
                }
                if(form && form.type=="outsideUrl"){
                    this.pk = bpmInst.busKey;
                    this.outSideUrl=form.component;
                    this.processConfig.formType="outsideUrl";
                    this.formComponent=this.loadUrlView();
                    this.getFormPc(form.id);
                    return;
                }
            }
        },
    }
}
</script>
<style scoped>
.tab-center-bg{
    width: 100%;
    height: calc( 100% - 45px );
    background: #fff;
    overflow: auto;
    position: relative;
}
.tabs-toolbar{
    height: 45px;
    display: flex;
    align-items: center;
}
.tab-center-content{
    display: inline-block;
    vertical-align: top;
    width: 100%;
    min-height: 100%;
    background: #F5F5F5;
    transition: all .5s;
}
.tab-center-content-show{
    width: calc( 100% - 340px );
}

.tab-center{
    box-sizing: border-box;
    max-width: 1300px;
    width: 80%;
    margin:0 auto 10px;
    min-height: calc( 100vh - 121px );
    background: #fff;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
}
.bpm-task-history{
    vertical-align: top;
    display: inline-block;
    background-color: #fff;
    width: 0;
    opacity: 0;
    transition: all .5s;
    min-height: 100%;
    overflow: hidden;
    position: relative;
    z-index: 11;
}
.bpm-history-button{
    top: 10px;
    right: 10px;
    position: absolute;
    width: 44px;
    height: 44px;
    background: #fff;
    box-shadow: 0 3px 10px 1px rgba(0,0,0,0.06);
    border-radius: 4px;
    z-index: 9;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.bpm-task-history-text{
    padding: 10px ;
    border-bottom: 1px solid #E8E8E8;
    font-size: 16px;
    color: #333;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
}
.bpm-history-close{
    display: inline-block;
    padding:0 4px;
    cursor: pointer;
}
.bpm-history-close:hover{
    color: #4d9eff;
}
.bpm-task-show{
    width:340px ;
    opacity: 1;
}

.rx-a-tabs >>> .ant-tabs-bar.ant-tabs-top-bar{
    margin-bottom: 0!important;
}
.bpm-task-content{
    height: calc( 100% - 64px);
}
.rx-a-tabs{
    width: 100%;
    height: 100%;
}
.formBox {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
</style>